import java.util.ArrayList;
import java.util.List;

public class Code_54 {
    /**
     * 四指针
     */
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return ans;

        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;

        while (true) {
            for (int i = left; i <= right; i++) { // 左->右
                ans.add(matrix[top][i]);
            }
            if (++top > bottom) break;
            for (int i = top; i <=bottom; i++) { // 上->下
                ans.add(matrix[i][right]);
            }
            if (--right < left) break;
            for (int i = right; i >= left; i--) { // 右->左
                ans.add(matrix[bottom][i]);
            }
            if (--bottom < top) break;
            for (int i = bottom; i >= top; i--) { // 下->上
                ans.add(matrix[i][left]);
            }
            if (++left > right) break;
        }
        return ans;
    }
}
